package com.duomi88.nettybio;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

/**
 * 模拟服务端
 * 公众号 duomi88
 */
public class SocketServer {
	
	private static Logger LOG  = Logger.getLogger(SocketServer.class);
	public static int PORT = 8888;
	private static ServerSocket serverSocket;
	
	/**
	 *  模拟服务端
	 * @param args
	 * @throws Exception
	 */
    public static void main( String[] args ) throws Exception
    {
        serverSocket = new ServerSocket(PORT);
        LOG.info("服务监听启动，端口："+PORT);
        while(true) {
        	try {
				Socket socket = serverSocket.accept();
				InputStream in = socket.getInputStream();
				int len;
				StringBuffer sb = new StringBuffer();
				byte[] bytes = new byte[1024];
				while((len = in.read(bytes))!=-1) {
					String bytesData = new String(bytes,0,len,"utf-8");
					sb.append(bytesData);
					if(bytesData.endsWith("END")) {
						//处理业务逻辑并返回消息
						handMsgAndResponse(socket,sb.toString());
						sb = null;
					}
				}
			} catch (Exception e) {
				LOG.error("处理客户端消息失败.",e);
			}
        	Thread.sleep(1000);
        }
    }

	private static void handMsgAndResponse(Socket socket,String sb) throws Exception {
		LOG.info("收到客户端消息："+sb.toString());
		String sn = sb.split("@")[0];
		String responseMsg = sn+"@服务端回复信息.";
		Thread.sleep(2000);//模拟业务处理
		socket.getOutputStream().write(responseMsg.getBytes("utf-8"));
		LOG.info("发送返回信息："+responseMsg);
	}
}
